/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entities;

import beans.BookDAO;
import beans.BookHelper;
import beans.CartDAO;
import beans.MessageBean;
import beans.SessionManager;
import beans.TestDao;
import beans.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table(name = "BOOKS")
@NamedQueries({
    @NamedQuery(name = "getBooksForTitle",
    query = "SELECT a FROM Book a WHERE a.title = :title"),
    @NamedQuery(name = "getAllBooks",
    query = "SELECT a FROM Book a"),
    @NamedQuery(name = "removeBookForTitle",
    query = "DELETE FROM Book a WHERE a.title = :title"),
    @NamedQuery(name = "removeBookForId",
    query = "DELETE FROM Book a WHERE a.id = :bookID"),
    @NamedQuery(name = "updateBookForId",
    query = "UPDATE Book a SET a.title = :title WHERE a.id = :bookID"),
    @NamedQuery(name = "updateBookForName",
    query = "UPDATE Book a SET a.title = :newTitle, a.price= :newBookPrice "
            + "WHERE a.title = :formerTitle AND a.price= :formerBookPrice ")
})
public class Book implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", nullable = false)
    private Long id;

    @Column(name="TITLE")
    private String title;

    @Column(name="PRICE")
    private Double price;

    @Column(name="DESCRIPTION")
    private String description;

    @ManyToMany(cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy="books")
    private Collection<Author> authors;
    
    @ManyToMany(cascade = CascadeType.ALL,mappedBy = "books")
    private List<Cart> carts;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy="books")
    private Collection<Orderr> orders;

    

    public Book() {
        authors = new ArrayList<Author>();
    }

    public Book(String title, Double price) {
        this.title = title;
        this.price = price;
        this.description = "";
        authors = new ArrayList<Author>();
    }

    public Book(String title, Double price, String description) {
        this.title = title;
        this.price = price;
        this.description = description;
        authors = new ArrayList<Author>();
    }
    
    public Book(String title, Double price, String description, Collection<Author> authors) {
        this.title = title;
        this.price = price;
        this.description = description;
        this.authors = authors;
    }
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Collection<Author> getAuthors() {
        return authors;
    }

    public void setAuthors(Collection<Author> authors) {
        this.authors = authors;
    }

    public void setOrders(Collection<Orderr> orders) {
        this.orders = orders;
    }

    public Collection<Orderr> getOrders() {
        return orders;
    }



    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Book)) {
            return false;
        }
        Book other = (Book) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entities.Book[id=" + id + "]";
    }
    
    public void putIntoCart() throws NonexistentEntityException, Exception
    {
        System.out.println("wkladamy do koszyka");
        //SessionManager sm = new SessionManager();
        if (SessionManager.getInstance().getSessionItem("client")==null) {
            //wypisz błąd...
        } else {
            Cart cart = (Cart) SessionManager.getInstance().getSessionItem("cart");
            cart.addBook(this);
            new CartDAO().edit(cart);      
        }
    }

    public void removeFromCart() throws NonexistentEntityException, Exception
    {
        System.out.println("usuwamy z koszyka");
        //SessionManager sm = new SessionManager();
        Cart cart = (Cart) SessionManager.getInstance().getSessionItem("cart");
        cart.removeBook(this);                      
        new CartDAO().edit(cart);// i zapisac w bazie przez dao
    }

    public boolean hasDescription()
    {
        if(description.equals(""))
            return true;
        else return false;
    }

    public void delete() throws NonexistentEntityException {
        //SessionManager sm = new SessionManager();
        //sm.clearSessionItem("book"); //sprawdzic czy potrzebne
        SessionManager.getInstance().setRequestItem("messageBean", new MessageBean("Usunięto książkę "+title));
        new BookDAO().destroy(id);
    }

    public String edit()
    {
        //SessionManager sm = new SessionManager();
        //sm.setRequestItem("book", this);
        SessionManager.getInstance().setRequestItem("bookHelper", new BookHelper(this));
        return "edit";
    }

    public void update() throws NonexistentEntityException, Exception {
        new BookDAO().edit(this); 
    }

    public void add() {
        //dodaj autorow..
        new BookDAO().create(this);
    }
    public String getAuthorsAsString()
    {
        String out = "";
        for(Author author: authors)
            out += author.getName() + " " +author.getSurname() + ", ";
        if(out.length() > 0)
            out = out.substring(0, out.length()-2);
        return out;
    }
}
